package com.lfy.fyadmin.controller;

import cn.dev33.satoken.exception.NotLoginException;
import com.lfy.fyadmin.common.BusinessException;
import com.lfy.fyadmin.common.ErrorCode;
import com.lfy.fyadmin.common.R;
//import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.http.converter.HttpMessageNotReadableException;


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> handleValidationException(MethodArgumentNotValidException ex) {
        String msg = ex.getBindingResult().getFieldError() != null ?
                ex.getBindingResult().getFieldError().getDefaultMessage() : "参数校验失败";
        return R.fail(ErrorCode.VALIDATE_FAILED.getCode(), msg);
    }


//    @ExceptionHandler(ConstraintViolationException.class)
//    public R<?> handleConstraintViolationException(ConstraintViolationException ex) {
//
//        return R.fail(ErrorCode.VALIDATE_FAILED.getCode(), ex.getMessage());
//    }

    @ExceptionHandler({MissingServletRequestParameterException.class, MissingPathVariableException.class, HttpMessageNotReadableException.class})
    public R<?> handleParamException(Exception ex) {
        return R.fail(ErrorCode.PARAM_ERROR.getCode(), "参数错误: " + ex.getMessage());
    }

//    @ExceptionHandler(AccessDeniedException.class)
//    public R<?> handleAccessDeniedException(AccessDeniedException ex) {
//        return R.fail(ErrorCode.FORBIDDEN.getCode(), "无权限");
//    }

//    @ExceptionHandler(AuthenticationException.class)
//    public R<?> handleAuthenticationException(AuthenticationException ex) {
//        return R.fail(ErrorCode.UNAUTHORIZED.getCode(), "未认证/未登录");
//    }

    //未登录
    @ExceptionHandler(NotLoginException.class)
    public R<?> handleBusinessException(NotLoginException ex) {

        return R.fail(ErrorCode.UNAUTHORIZED.getCode(), ErrorCode.UNAUTHORIZED.getMsg());
    }


    @ExceptionHandler(BusinessException.class)
    public R<?> handleBusinessException(BusinessException ex) {
        return R.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception ex) {
        ex.printStackTrace();
        return R.fail(ErrorCode.SERVER_ERROR.getCode(), "服务器内部错误: " + ex.getMessage());
    }
} 